package org.leiyang.gateway.handler;

import org.leiyang.common.dtos.MsgServerInfo;
import org.leiyang.gateway.service.MsgServerServiceImpl;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * 获取当前连接数最少的msg_server
 */
@Component
public class ChooseIdleMsgServerHandler implements HandlerFunction<ServerResponse> {

    private final MsgServerServiceImpl msgServerService;

    public ChooseIdleMsgServerHandler(MsgServerServiceImpl msgServerService) {
        this.msgServerService = msgServerService;
    }

    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        Mono<MsgServerInfo> msgServerGetMono = msgServerService.chooseMostIdleServer();
        return msgServerGetMono.flatMap(msgServerInfo ->
                ServerResponse.status(HttpStatus.OK)
                        .body(BodyInserters.fromValue(msgServerInfo))
        );
    }
}
